import strJobTypePageHtml from "./JobTypePage.html";
import { DomUtils } from "../../utils/DomUtils";
import { jobTypeService } from "../../services/jobTypeService.js";

export class JobTypePage {
  constructor() {
    this.currentPage = 1;
    this.pageSize = 10;
    this.searchKeyword = "";
    this.modal = null;
    this.isSearching = false;
    this.modalInstance = null;
    this.modalBackdrop = null;
    this.currentEditId = null;
    this.totalPages = 1;
    this.totalItems = 0;
  }

  render() {
    const dom = DomUtils.convertToDom(strJobTypePageHtml);
    this._bindElements(dom);
    this._bindEvents(dom);
    this._loadData();
    return dom;
  }

  _bindElements(dom) {
    this.tableBody = dom.querySelector("#jobTypeTableBody");
    this.pagination = dom.querySelector("#pagination");
    this.searchInput = dom.querySelector("#searchInput");
    this.searchType = dom.querySelector("#searchType");
    this.searchBtn = dom.querySelector("#searchBtn");
    this.modalElement = dom.querySelector("#jobTypeModal");
    this.cardHeader = dom.querySelector(".card-header");
  }

  async _loadData() {
    try {
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
      };

      const result = await jobTypeService.getJobTypes(params);
      this._renderTable(result.items);

      this.totalPages = result.totalPages;
      this.totalItems = result.total;
      this._renderPagination();
      this._showPagination();

      this._resetBatchDeleteButton();
    } catch (error) {
      console.error("加载工作类型数据失败:", error);
      this._showError("加载工作类型数据失败：" + error.message);
    }
  }

  _renderTable(jobTypes) {
    this.tableBody.innerHTML =
      jobTypes.length > 0
        ? jobTypes
            .map(
              (jobType) => `
          <tr>
            <td>
              <div class="custom-checkbox custom-control">
                <input type="checkbox" class="custom-control-input job-type-checkbox" id="job-type-${
                  jobType.id
                }" data-id="${jobType.id}">
                <label for="job-type-${
                  jobType.id
                }" class="custom-control-label"></label>
              </div>
            </td>
            <td>${jobType.id}</td>
            <td>${jobType.jobType || "-"}</td>
            <td>
              <button class="btn btn-primary btn-sm edit-btn" data-id="${
                jobType.id
              }">
                <i class="fas fa-edit"></i> 编辑
              </button>
              <button class="btn btn-danger btn-sm delete-btn" data-id="${
                jobType.id
              }">
                <i class="fas fa-trash"></i> 删除
              </button>
            </td>
          </tr>
        `
            )
            .join("")
        : '<tr><td colspan="4" class="text-center">未找到工作类型数据</td></tr>';
  }

  _renderPagination() {
    let startPage = Math.max(1, this.currentPage - 2);
    let endPage = Math.min(this.totalPages, startPage + 4);

    if (endPage - startPage < 4) {
      startPage = Math.max(1, endPage - 4);
    }

    let pages = [];

    pages.push(`
      <li class="page-item ${this.currentPage === 1 ? "disabled" : ""}">
        <a class="page-link" href="#" data-page="1" title="首页">
          <i class="fas fa-angle-double-left"></i>
        </a>
      </li>
    `);

    pages.push(`
      <li class="page-item ${this.currentPage === 1 ? "disabled" : ""}">
        <a class="page-link" href="#" data-page="${
          this.currentPage - 1
        }" title="上一页">
          <i class="fas fa-angle-left"></i>
        </a>
      </li>
    `);

    for (let i = startPage; i <= endPage; i++) {
      pages.push(`
        <li class="page-item ${i === this.currentPage ? "active" : ""}">
          <a class="page-link" href="#" data-page="${i}">${i}</a>
        </li>
      `);
    }

    pages.push(`
      <li class="page-item ${
        this.currentPage === this.totalPages ? "disabled" : ""
      }">
        <a class="page-link" href="#" data-page="${
          this.currentPage + 1
        }" title="下一页">
          <i class="fas fa-angle-right"></i>
        </a>
      </li>
    `);

    pages.push(`
      <li class="page-item ${
        this.currentPage === this.totalPages ? "disabled" : ""
      }">
        <a class="page-link" href="#" data-page="${
          this.totalPages
        }" title="末页">
          <i class="fas fa-angle-double-right"></i>
        </a>
      </li>
    `);

    this.pagination.innerHTML = pages.join("");
  }

  _bindEvents(dom) {
    this.searchBtn?.addEventListener("click", async () => {
      const searchValue = this.searchInput.value.trim();
      const searchType = this.searchType.value;

      if (!searchValue) {
        this._showError("请输入搜索内容");
        return;
      }

      try {
        let jobTypes;
        if (searchType === "id") {
          const id = parseInt(searchValue);
          if (isNaN(id)) {
            this._showError("请输入有效的工作类型ID");
            return;
          }
          const jobType = await jobTypeService.getJobType(id);
          jobTypes = jobType ? [jobType] : [];
        } else {
          // 获取所有工作类型并在前端进行模糊匹配
          const allJobTypes = await jobTypeService.getJobTypes({
            page: 1,
            pageSize: 1000,
          });
          jobTypes = allJobTypes.items.filter((jt) => {
            const searchText = searchValue.toLowerCase();
            const jobTypeText = (jt.jobType || "").toLowerCase();
            return jobTypeText.includes(searchText);
          });
        }

        if (jobTypes.length > 0) {
          this._renderTable(jobTypes);
          this._hidePagination();
          this._addBackButton();
        } else {
          this._showError(
            `未找到${
              searchType === "id" ? "工作类型ID" : "工作类型名称"
            }包含 "${searchValue}" 的工作类型`
          );
        }
      } catch (error) {
        console.error("Error searching job types:", error);
        this._showError("查询失败：" + error.message);
      }
    });

    // 搜索输入框回车事件
    this.searchInput?.addEventListener("keypress", (e) => {
      if (e.key === "Enter") {
        this.searchBtn.click();
      }
    });

    this.searchInput?.addEventListener("input", (e) => {
      const searchValue = e.target.value.trim();
      if (searchValue.length >= 2) {
        this.searchBtn.click();
      }
    });

    this.pagination?.addEventListener("click", (e) => {
      e.preventDefault();
      if (e.target.tagName === "A") {
        this.currentPage = parseInt(e.target.dataset.page);
        this._loadData();
      }
    });

    dom
      .querySelector("#addJobTypeBtn")
      ?.addEventListener("click", () => this._showJobTypeModal());

    this.tableBody?.addEventListener("click", async (e) => {
      const btn = e.target;
      const id = btn.dataset.id;

      if (btn.classList.contains("delete-btn")) {
        if (confirm("确认删除该工作类型？")) {
          await jobTypeService.deleteJobType(id);
          this._loadData();
        }
      } else if (btn.classList.contains("edit-btn")) {
        this._showJobTypeModal(id);
      }
    });

    const form = dom.querySelector("#jobTypeForm");
    form?.addEventListener("submit", async (e) => {
      e.preventDefault();
      await this._handleFormSubmit(form, this.currentEditId);
    });

    dom.querySelector("#modalClose")?.addEventListener("click", () => {
      this._cleanupModal();
    });

    dom
      .querySelector('[data-dismiss="modal"]')
      ?.addEventListener("click", () => {
        this._cleanupModal();
      });

    const selectAllCheckbox = dom.querySelector("#selectAll");
    selectAllCheckbox?.addEventListener("change", (e) => {
      const checkboxes = dom.querySelectorAll(".job-type-checkbox");
      checkboxes.forEach((checkbox) => {
        checkbox.checked = e.target.checked;
      });
      this._updateBatchDeleteButton();
    });

    this.tableBody?.addEventListener("change", (e) => {
      if (e.target.classList.contains("job-type-checkbox")) {
        this._updateBatchDeleteButton();
      }
    });

    const batchDeleteBtn = dom.querySelector("#batchDeleteBtn");
    batchDeleteBtn?.addEventListener("click", async () => {
      const selectedIds = Array.from(
        dom.querySelectorAll(".job-type-checkbox:checked")
      ).map((checkbox) => parseInt(checkbox.dataset.id));

      if (selectedIds.length === 0) {
        alert("请选择要删除的工作类型");
        return;
      }

      if (!confirm(`确定要删除选中的 ${selectedIds.length} 个工作类型吗？`)) {
        return;
      }

      try {
        await jobTypeService.batchDeleteJobTypes(selectedIds);
        this._loadData();
        alert("批量删除成功");
      } catch (error) {
        console.error("批量删除失败:", error);
        alert("批量删除失败：" + error.message);
      }
    });
  }

  _resetBatchDeleteButton() {
    const batchDeleteBtn = document.querySelector("#batchDeleteBtn");
    batchDeleteBtn.disabled = true;
    batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 批量删除`;
  }

  _updateBatchDeleteButton() {
    const batchDeleteBtn = document.querySelector("#batchDeleteBtn");
    const selectedCount = document.querySelectorAll(
      ".job-type-checkbox:checked"
    ).length;
    batchDeleteBtn.disabled = selectedCount === 0;
    if (selectedCount > 0) {
      batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 批量删除(${selectedCount})`;
    } else {
      batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 批量删除`;
    }
  }

  _addBackButton() {
    // 如果返回按钮已经存在，先移除它
    const existingBackButton =
      this.searchBtn.parentNode.querySelector(".btn-secondary");
    if (existingBackButton) {
      existingBackButton.remove();
    }

    // 添加返回按钮
    const backButton = document.createElement("button");
    backButton.className = "btn btn-secondary btn-sm ml-2";
    backButton.innerHTML = '<i class="fas fa-arrow-left"></i> 返回列表';
    backButton.onclick = () => {
      this._loadData();
      backButton.remove();
    };

    this.searchBtn.parentNode.insertBefore(
      backButton,
      this.searchBtn.nextSibling
    );
  }

  _showError(message) {
    this.tableBody.innerHTML = `
      <tr><td colspan="4" class="text-center text-danger">${message}</td></tr>
    `;
    this._addBackButton();
  }

  _hidePagination() {
    this.pagination.classList.add("d-none");
  }

  _showPagination() {
    this.pagination.classList.remove("d-none");
  }

  async _showJobTypeModal(id = null) {
    this.currentEditId = id;
    if (!this.modalInstance) {
      this.modalInstance = new bootstrap.Modal(this.modalElement, {
        backdrop: "static",
      });

      this.modalElement.addEventListener("hidden.bs.modal", () => {
        this.modalInstance = null;
      });
    }

    const form = this.modalElement.querySelector("#jobTypeForm");
    const title = this.modalElement.querySelector(".modal-title");
    const isEdit = !!id;

    title.textContent = isEdit ? "编辑工作类型" : "新增工作类型";
    form.reset();

    if (isEdit) {
      try {
        const jobType = await jobTypeService.getJobType(id);
        form.querySelector("#jobType").value = jobType.jobType || "";
      } catch (error) {
        alert("加载工作类型信息失败");
        return;
      }
    }

    this.modalInstance.show();
  }

  _cleanupModal() {
    if (this.modalInstance) {
      this.modalInstance.hide();
    }
    this.currentEditId = null;
  }

  async _handleFormSubmit(form, id) {
    if (!form.checkValidity()) {
      form.classList.add("was-validated");
      return;
    }

    const formData = {
      jobType: form.querySelector("#jobType").value.trim() || "",
    };

    try {
      if (id) {
        const jobTypeId = parseInt(id);
        if (isNaN(jobTypeId)) {
          throw new Error("无效的工作类型ID");
        }
        await jobTypeService.updateJobType(jobTypeId, formData);
      } else {
        await jobTypeService.createJobType(formData);
      }

      if (this.modalInstance) {
        this.modalInstance.hide();
      } else {
        this._cleanupModal();
      }

      this._loadData();
    } catch (error) {
      alert(`操作失败: ${error.message}`);
    } finally {
      form.classList.remove("was-validated");
    }
  }
}
